<?php
namespace Wap\Controller;
use Common\Controller\FirstendController;

import("ITK.Itklib.itaoke_https");
import("ITK.ORG.Pinyin");

class ItemController extends FirstendController {

	private $_itkconfig = null;
	public function _initialize() {
		parent::_initialize();
		$this->_mod = D('Items');
		$this->_cate_mod = D('ItemsCate');
		$this->assign('nav_curr', 'index');
		//访问者控制
		if (!$this->visitor->is_login && in_array(ACTION_NAME, array('delete', 'comment','delcol','mycol'))) {
			IS_AJAX && $this->ajaxReturn(0, L('login_please'));
			$this->redirect('user/login');
		}
		if(C('itk_site_cache')){
			$file = 'ItemsSite';
			if(false === $this->_itkconfig = S($file)){
				$api_config = M('ItemsSite')->where(array('code' => 'itaoke'))->getField('config');
				$this->_itkconfig = unserialize($api_config);
				S($file,$this->_itkconfig);
			}
		}else{
			$api_config = M('ItemsSite')->where(array('code' => 'itaoke'))->getField('config');
			$this->_itkconfig = unserialize($api_config);
		} 
		
	}

// 	private function checkIsWechat(){
// 		$user_agent = $_SERVER['HTTP_USER_AGENT'];
// 		if (strpos($user_agent, 'MicroMessenger') === false) {
// 			return false;
// 		}
// 		return true;
// 	}
	
	public function _empty(){
		$p		= I('p',1 ,'intval'); //页码
		$sort	= I('sort', 'default', 'trim'); //排序
		$cid	= I('cid',0,'intval');
		$k		= I('k','');
		$price	= I('price',0,'intval');
		
		$id = I('id', '','trim');
		!$id && $this->_404();

		$item = $this->_mod->where(array('id' => $id))->find();
		if(!$item){
			redirect(U('Index/index'));	
		}
		
		if (!$item['desc']) {
			$infoUrl = 'http://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?data=%7B%22item_num_id%22%3A%22' . $item['num_iid'] . '%22%7D';
			$itaoke_https = new \itaoke_https();
			$itaoke_https->fetch($infoUrl);
			$source = $itaoke_https->results;
			if (!$source) {
				$source = file_get_contents($infoUrl);
			}
			$comlist = json_decode($source, true);
			$tm = $comlist['data']['images'];
			$onepic = '<img class="lazy" src=' . $tm[0] . '>';
			$item['desc'] = implode('', $tm);
			foreach ($tm as $sms) {
				if (strpos($item['desc'], $sms)) {
					$imgurl = '<img class="lazy" src=' . $sms . '>';
					$item['desc'] = str_replace($sms, $imgurl, $item['desc']);
					$item['desc'] = str_replace($tm[0], '', $item['desc']);
				}
			}
			$item['desc'] = $onepic . '' . $item['desc'];
			$data['desc'] = $item['desc'];
			$this->_mod->where(array('id' => $id))->save($data);
		}
		else
		{
			$item['desc']=htmlspecialchars_decode($item['desc']);
		}
		
		$isWechat = checkIsWechat();
		if($isWechat){
			$item['iswechat']=1;
			$url_type= C('itk_weixin_url_form');	// 0 - 二合一链接 1 淘口令 2 淘口令+二合一
		}else{
			$item['iswechat']=0;
			$url_type= C('itk_wap_url_form');		// 0 - 二合一链接 1 淘口令
		}
		
		$item['url_type']=$url_type;
		if($url_type == 1 || $url_type ==2){	// 当淘口令时判断当前item是否有淘口令
			if( !$item['taotoken'] ){
				$apiparams=array(
					'pic'=>$item['pic_url'],
					'qurl'=>$item['quanurl'],
					'num_iid'=>$item['num_iid'],
					'title'=>$item['title'],
					'dx'=>$item['dx'],
				    'turl'=>$item['click_url'],
				);
				$item['taotoken']=$this->transform($apiparams);
				if($item['taotoken'])
					$this->_mod->where(array('id' => $id))->save(array('taotoken'=>$item['taotoken']));
			}		
		}

		$item['ulandUrl']=$item['click_url'] ? urlencode($item['click_url']) : urlencode(buildUland($item['num_iid'],$item['quanurl'],$item['dx']));
		
		
		$item['after_price']=$item['coupon_price']-$item['quan'];
		$this->assign('item', $item);
		if(C('itk_item_hit')){
			$hits_data = array('hits'=>array('exp','hits+1'));
			if(strlen($id)>9){
				$this->_mod->where(array('num_iid'=>$id))->setField($hits_data);
			}else{
				$this->_mod->where(array('id'=>$id))->setField($hits_data);
			}
		}
		
		$this->assign('p',$p);
		$this->assign('sort',$sort);
		$this->assign('cid',$cid);
		$this->assign('id',$id);
		$this->assign('k',$k);
		$this->assign('price',$price);
		$this->assign('tp',S('totalPages')=='' ? 50:S('totalPages'));
		
		$this->_config_seo(C('itk_seo_config.item'), array(
            'title' => $item['title'],
            'intro' => $item['intro'],
			'price' => $item['price'],
			'coupon_price' => $item['coupon_price'],
            'seo_title' => $item['seo_title'],
            'seo_keywords' => $item['seo_keys'],
            'seo_description' => $item['seo_desc'],
		));

		$this->display('index');
		
    }

	/**
	 * 商品详细页
	 */
	public function index() {
		$p		= I('p',1 ,'intval'); //页码
		$sort	= I('sort', 'default', 'trim'); //排序
		$cid	= I('cid',0,'intval');
		$k		= I('k','');
		$price	= I('price',0,'intval');
		
		$id = I('id', '','trim');
		!$id && $this->_404();

		$item = $this->_mod->where(array('id' => $id))->find();
		if(!$item){
			redirect(U('Index/index'));	
		}
		$nodesc=0;		// 默认有desc
		if (!$item['desc']) {
			$infoUrl = 'http://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?data=%7B%22item_num_id%22%3A%22' . $item['num_iid'] . '%22%7D';
			$itaoke_https = new \itaoke_https();
			$itaoke_https->fetch($infoUrl);
			$source = $itaoke_https->results;
			$comlist = json_decode($source, true);
			$isGetDesc = false;
			if(is_array($comlist)){
				if($comlist[ret][0]=='SUCCESS::接口调用成功'){
					$isGetDesc=true;
				}
			}
			if (!$isGetDesc) {
				$UserAgent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
				$curl = curl_init();
				curl_setopt($curl, CURLOPT_URL, $infoUrl);
				curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
				curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
				curl_setopt($curl, CURLOPT_HEADER, 0);
				curl_setopt($curl, CURLOPT_USERAGENT, $UserAgent);
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
				$data = curl_exec($curl);
				$comlist = json_decode($data, true);
				if(is_array($comlist)){
					if($comlist[ret][0]=='SUCCESS::接口调用成功'){
						$isGetDesc=true;
					}
				}
			}

			if($isGetDesc){
				$tm = $comlist['data']['images'];
				$onepic = '<img class="lazy" src=' . $tm[0] . '>';
				$item['desc'] = implode('', $tm);
				foreach ($tm as $sms) {
					if (strpos($item['desc'], $sms)) {
						$imgurl = '<img class="lazy" src=' . $sms . '>';
						$item['desc'] = str_replace($sms, $imgurl, $item['desc']);
						$item['desc'] = str_replace($tm[0], '', $item['desc']);
					}
				}
				$item['desc'] = $onepic . '' . $item['desc'];
				$_data['desc'] = $item['desc'];
				$this->_mod->where(array('id' => $id))->save($_data);
			}else{
				$nodesc=1;		// 无详情获取不到了
			}
		}
		else
		{
			$item['desc']=htmlspecialchars_decode($item['desc']);
		}
		
		$this->assign('nodesc',$nodesc);
		$isWechat = checkIsWechat();
		if($isWechat){
			$item['iswechat']=1;
			$url_type= C('itk_weixin_url_form');	// 0 - 二合一链接 1 淘口令 2 淘口令+二合一
		}else{
			$item['iswechat']=0;
			$url_type= C('itk_wap_url_form');		// 0 - 二合一链接 1 淘口令
		}
		
		$item['url_type']=$url_type;
		if($url_type == 1 || $url_type ==2){	// 当淘口令时判断当前item是否有淘口令
			if( !$item['taotoken'] ){
				$apiparams=array(
					'pic'=>$item['pic_url'],
					'qurl'=>$item['quanurl'],
					'num_iid'=>$item['num_iid'],
					'title'=>$item['title'],
					'dx'=>$item['dx'],
				    'turl'=>$item['click_url'],
				);
				$item['taotoken']=$this->transform($apiparams);
				if($item['taotoken'])
					$this->_mod->where(array('id' => $id))->save(array('taotoken'=>$item['taotoken']));
			}		
		}

		// 2018.01.03
		// 是否开启自动转链接
		if(C('itk_auto_privilege') ==1 && !$item['click_url']){
			$qUrl=htmlspecialchars_decode($item['quanurl']);
			$geturl = parse_url($qUrl);
			$paramid = convertUrlQuery($geturl['query']);
			$item['click_url'] = autoPrivilege($item['id'],$item['num_iid'] , $paramid['activityId'] == '' ? $paramid['activity_id']:$paramid['activityId'] );
		}
		// 6.30 新增高效链接跳转
		$item['ulandUrl']=$item['click_url'] ? urlencode($item['click_url']) : urlencode(buildUland($item['num_iid'],$item['quanurl'],$item['dx']));
		
		$item['after_price']=$item['coupon_price']-$item['quan'];
		$this->assign('item', $item);
		if(C('itk_item_hit')){
			$hits_data = array('hits'=>array('exp','hits+1'));
			if(strlen($id)>9){
				$this->_mod->where(array('num_iid'=>$id))->setField($hits_data);
			}else{
				$this->_mod->where(array('id'=>$id))->setField($hits_data);
			}
		}
		
		$this->assign('p',$p);
		$this->assign('sort',$sort);
		$this->assign('cid',$cid);
		$this->assign('id',$id);
		$this->assign('k',$k);
		$this->assign('price',$price);
		$this->assign('tp',S('totalPages')=='' ? 50:S('totalPages'));
		
		$this->_config_seo(C('itk_seo_config.item'), array(
            'title' => $item['title'],
            'intro' => $item['intro'],
			'price' => $item['price'],
			'coupon_price' => $item['coupon_price'],
            'seo_title' => $item['seo_title'],
            'seo_keywords' => $item['seo_keys'],
            'seo_description' => $item['seo_desc'],
		));
		$this->getRandom($item['cate_id']);
		if(C('itk_wap_detail')==1)
			$this->display('detail');
		else
			$this->display('index');
	}

	public function getRandom($cate_id){
//		$_pre=C('DB_PREFIX');
//		$res =M()->query("SELECT * FROM {$_pre}items AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM {$_pre}items )-(SELECT MIN(id) FROM {$_pre}items ))+(SELECT MIN(id) FROM {$_pre}items )) AS id) AS t2 WHERE t1.id >= t2.id and t1.isq =1 and t1.cate_id={$cate_id} and t1.coupon_end_time < unix_timestamp(now()) ORDER BY t1.id LIMIT 12");

		$items = M('Items');
		$num=12;
		$where['cate_id']=$cate_id;
		$where['isq']=1;
		$where['status']='underway';
		$countcus=$items->where($where)->count();
		
		if($countcus==0){
			unset($where['cate_id']);
			$countcus=$items->where($where)->count();
		}
		$res=array();
		$min=$items->where($where)->min('id');
		$max=$items->where($where)->max('id');
		if($countcus<$num){
			$num=$countcus;
		}
		$i=1;
		$flag=0;
		while($i<=$num){
			$rundnum=rand($min, $max);
			if($flag!=$rundnum){
				if($addlink=$items->getById($rundnum) ){
					$res[]=$addlink;
					$flag=$rundnum;
					$i++;
				}
			}
		}
		$this->assign('random',$res);		
	}
	/**
	 * 调用爱淘客api获取佣金淘口令
	 */
	private function transform($aprams){
		$taodianjin = C('itk_taojindian_html');
		if (strpos($taodianjin, "text/javascript")) {
			$pid = get_word($taodianjin, 'pid: "' , '"');
		} else {
			$pid = $taodianjin;
		}
		// 不走定向时 默认鹊桥推广
		if($aprams['dx'] != 1 && C('itk_queqiao_pid')!=''){
			$pid = C('itk_queqiao_pid');
		}		
		if (!$pid) {
			return;
		}
		$aprams['pid']=$pid;
		$tb_top = $this->_get_itk_top();
		$req = $tb_top->load_api('ItaokeTaotokenRequest');
		$req->setFields($aprams);				// 设置采集数据分类ID
		$resp = (array)$tb_top->execute($req);
		if($resp['status'] != '0000')
		{
			return;
		}
		return $resp['data'];
	}
	/**
	 * 爱淘客开放平台
	 */
	private function _get_itk_top() {
		vendor('Itaoke.TopClient');
		vendor('Itaoke.RequestCheckUtil');
		vendor('Itaoke.Logger');
		$tb_top = new \TopClient;
		$tb_top->appkey = $this->_itkconfig['app_key'];
		$tb_top->secretKey = $this->_itkconfig['app_secret'];
		return $tb_top;
	}

	public function ajaxUpItemDesc(){
		if(!IS_AJAX) return;
		$image=I('post.image');
		$id=I('post.id');
		$images='';
		for($i=0;$i<count($image);$i++){
			$images.=$image[$i];
		}
		$data['desc'] = $images;
		$this->_mod->where(array('id' => $id))->save($data);
	}
}